import React, { FC, useContext, useState, ReactNode, useMemo, FunctionComponentElement, useRef } from 'react'
import classNames from 'classnames'
import { MenuContext, IMenuContext } from './menu'
import { MenuItemProps } from './menuItem'
import Transition from '../Transition/transition'
import Icon from '../Icon/icon'

export interface SubMenuProps {
  index?: string
  title: string // 菜单选项的文字
  className?: string
  children?: ReactNode
}

export const SubMenu = ({
  index, // 激活菜单选项的索引
  title,
  children,
  className
}: SubMenuProps) => {
  const context = useContext(MenuContext) as IMenuContext
  const openedSubMenus = context.defaultOpenSubMenus as Array<string> // 获取默认展开的菜单
  const isOpend = index && context.mode === 'vertical' ? openedSubMenus.includes(index) : false // 判断是否展开
  const [menuOpen, setOpen] = useState(isOpend) // 控制展开和收起
  const nodeRef = useRef(null)
  // 类名
  const classes = classNames('menu-item submenu-item', className, {
    'is-active': context.index === index, // 判断是否激活
    'is-opened': menuOpen, // 判断是否展开
    'is-vertical': context.mode === 'vertical' // 判断是否垂直模式
  })
  // 点击事件
  const handleClick = (e: React.MouseEvent) => {
    // if (context.mode !== 'vertical') return
    e.preventDefault()
    setOpen(!menuOpen)
    context?.onSelect(index as string)
  }

  let timer: any
  const handleMouse = (e: React.MouseEvent, toggle: boolean) => {
    setOpen(toggle)
    clearTimeout(timer)
    e.preventDefault()
    timer = setTimeout(() => {
      setOpen(toggle)
    }, 300)
  }
  // 水平方向添加 hover 事件
  const hoverEvents =
    context.mode !== 'vertical'
      ? {
          onMouseEnter: (e: React.MouseEvent) => {
            handleMouse(e, true)
          },
          onMouseLeave: (e: React.MouseEvent) => {
            handleMouse(e, false)
          }
        }
      : {}
  // 渲染子菜单
  const renderChildren = () => {
    const subMenuClasses = classNames('fucking-submenu', {
      'menu-opened': menuOpen // 判断是否展开
    })
    const childrenComponent = React.Children.map(children, (child, i) => {
      const childElement = child as FunctionComponentElement<MenuItemProps>
      if (childElement.type.displayName === 'MenuItem') {
        return React.cloneElement(childElement, {
          index: `${index}-${i}` // 给子菜单添加索引
        })
      } else {
        console.error('Warning: SubMenu has a child which is not a MenuItem component')
      }
    })
    return (
      <Transition
        nodeRef={nodeRef} // 将 ref 传递给 CSSTransition 组件
        in={menuOpen}
        timeout={300}
        // animation="zoom-in-top"
      >
        <ul
          ref={nodeRef} // 获取 DOM 节点
          className={subMenuClasses}
        >
          {childrenComponent}
        </ul>
      </Transition>
    )
  }
  return (
    <li key={index} className={classes} {...hoverEvents}>
      <div className="submenu-title" onClick={handleClick}>
        {title}
        <Icon
          icon="angle-down" // 图标名称
          className="arrow-icon"
          theme="dark" // 主题（颜色）
          size="1x" // 使用 1x 代替 16px
        />
      </div>
      {renderChildren()}
    </li>
  )
}
SubMenu.displayName = 'SubMenu'
export default SubMenu
